<template>
  <div class="login-container">
    <el-form ref="loginFromRef" class="login-form" :model="loginForm" :rules="loginRules">
      <div class="title-container">
        <h3 class="title">MTSAS后台管理系统</h3>
      </div>
      <el-form-item prop="username" style="display: flex;flex-direction: row">
          <Icon icon="username" />
        <el-input  placeholder="请输入用户名" name="username" type="text" v-model="loginForm.username" @keyup.enter.native="handleLogin"/>
      </el-form-item>
      <el-form-item prop="password">
        <Icon icon="lock" />
        <el-input placeholder="请输入密码" name="password" :type="passwordType" v-model="loginForm.password" @keyup.enter.native="handleLogin"/>
        <span class="show-pwd">
          <Icon :icon="passwordType === 'password' ? 'eye' : 'eye-open'"
              @click.prevent="onChangePwdType" />
        </span>
      </el-form-item>

      <el-form-item class="code-box" prop="captcha_code">
        <Icon icon="verify" />
        <el-input
            placeholder="图形验证码"
            v-model="loginForm.captcha_code" name="captcha_code" class="code-input" maxlength="4" @keyup.enter.native="handleLogin">
        </el-input>
        <canvas ref="captchaCanvas" @click.prevent="getCodeImg"></canvas>  
      </el-form-item>
      <el-button type="primary" style="width: 100%; margin-bottom: 30px;" :loading="loading"
                 @click.prevent="handleLogin"
                 size="large">
        <span v-if="!loading">登 录</span>
        <span v-else>登 录 中...</span>
      </el-button>
    </el-form>
    <!--  底部  -->
    <footer>
      <p><span>MTSAS影界指南</span></p>
    </footer>
  </div>
</template>

<script setup>
// import CryptoJS from 'crypto-js';
import {ref, onMounted} from 'vue'
import Icon from '@/components/Icon.vue'
import {validatePassword, validateCode} from './rules'
import {getCode,login} from '@/api/index.js';
import {useUserStore} from '@/store/modules/user.js';
import router from '@/router';
import {ElMessage,ElForm,ElFormItem,ElButton,ElInput} from "element-plus";
import CryptoJS from 'crypto-js'; 

onMounted(() => {
  getCodeImg()
})
const code_net = ref('');

//数据源
const loginForm = ref({
  username: '',
  password: '',
  captcha_code: '',
})
//验证规则
const loginRules = ref({
  username: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入用户名'
    },

  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      validator: validatePassword()
    },

  ],
  captcha_code: [
    {
      required: true,
      trigger: 'blur',
      validator: validateCode()
    },
  ],
})

// 处理密码框文本显示状态
const passwordType = ref('password')
const onChangePwdType = () => {
  if (passwordType.value === 'password') {
    passwordType.value = 'text'
  } else {
    passwordType.value = 'password'
  }
}

// 登录动作处理
const loading = ref(false)
const loginFromRef = ref(null)
const store = useUserStore();
const captchaCanvas = ref(null);
/**
 * 登录
 */
const handleLogin = () => {
  loginFromRef.value.validate(valid => {
    if (!valid) return;
    let inputCode = loginForm.value.captcha_code;
   // let encInputCode= CryptoJS.SHA256(inputCode).toString();
    if(inputCode != code_net.value){
      ElMessage.error("验证码错误！");
      getCodeImg();
      return;
    }
    loading.value = true;
    //调用登录接口
    login(loginForm.value).then(res=>{
      if(res.status.code != 200){
        getCodeImg();
        ElMessage.error(res.status.msg);
        loading.value = false;
        return;
      }
      
      store.setUser(res.data);
      loading.value = false;
      router.push('/home');
      
    }).catch(err=>{
      loading.value = false;
    })
  })
}
/**
 * 获取图形验证码
 */
const getCodeImg = () => {
  // 获取图形验证码
  getCode({})
      .then(res => {
        code_net.value = res.data.code;
        drawCaptcha();
      })
      .catch(err => {
      })
}
// 绘制图形验证码
const drawCaptcha = () => {
  let ctx = captchaCanvas.value.getContext('2d');
  ctx.clearRect(0,0, captchaCanvas.value.width, captchaCanvas.value.height);  
  ctx.font = '100px Arial';  
  ctx.fillStyle = 'black';  
  ctx.fillText(code_net.value, 20, 100);  
  const noisePoints = getRandomNoisePoints(captchaCanvas.value);  
      noisePoints.forEach(point => {  
        ctx.fillStyle = getRandomColor(); 
        ctx.beginPath();   
        ctx.arc(point.x, point.y, point.size, 0, Math.PI * 2); // 使用arc函数绘制圆形噪点  
        ctx.fill();  
      });    
      ctx.draw();
}
// 随机生成噪点
const getRandomNoisePoints = canvas => {  
      const points = [];  
      const width = canvas.width;  
      const height = canvas.height;  
      const numPoints = Math.floor(Math.random() * 21 + 12); // 随机生成2-5个噪点  
      for (let i = 0; i < numPoints; i++) {  
        const size = Math.floor(Math.random() * 10 + 1); // 随机生成小、中、大噪点  
        const x = Math.floor(Math.random() * width); // 在画布上随机选择一个位置作为噪点的中心点x坐标  
        const y = Math.floor(Math.random() * height); // 在画布上随机选择一个位置作为噪点的中心点y坐标  
        points.push({ x, y, size });  
      }  
      return points;  
    };  
  // 随机生成噪点的颜色
    const getRandomColor = () => {  
      const r = Math.floor(Math.random() * 256); // 随机生成一个0-255的红色值  
      const g = Math.floor(Math.random() * 256); // 随机生成一个0-255的绿色值  
      const b = Math.floor(Math.random() * 256); // 随机生成一个0-255的蓝色值  
      return `rgb(${r},${g},${b})`; // 返回一个随机的RGB颜色值  
    };  
</script>

<style lang="scss" scoped>
$bg: #5268bc;
$dark_gray: #889aa4;
$light_gray: #ff0000;
$cursor: #000000;
$txt_color: #333;

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  flex-direction: column;
  background-image: url("../../assets/login-background.jpg");
  background-size: cover;
  //background: radial-gradient(ellipse at bottom, #1b2735 0%, #090a0f 100%);
  .login-form {
    position: relative;
    width: 420px;
    max-width: 100%;
    padding: 35px;
    margin: 0 auto;
    overflow: hidden;
    background: #ffffffb3;
    backdrop-filter: blur(50px);
    margin-top: 3%;
    border-radius: 6px;
    :deep(.el-form-item) {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }

    :deep(.el-input) {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        padding: 12px 5px 12px 15px;
        height: 47px;
        caret-color: $cursor;
        color: $txt_color;
      }

      .el-input__wrapper {
        background: none;
        box-shadow: none;
        width: 90%;
        height: 47px;
      }

    }
  }


  .icon-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $txt_color;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  canvas{
    position: absolute;
    width: 64px;
    height: 47px;
    right: 0;
    background:#ffffffb0;
    border-bottom-right-radius: 5px;
    border-top-right-radius: 5px;
  }
  .code-box {
    position: relative;
    .code-img {
      position: absolute;
      width: 60px;
      right: 0;
      top: 6px;
      font-size: 22px;
      background: transparent;

    }
  }
  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
  }
}

</style>
